/*
 * Copyright (C) 2010 The MobileSecurePay Project
 * All right reserved.
 * author: shiqun.shi@alipay.com
 */

package com.djsearch.alipay;

import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.djsearch.R;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.Toast;

public class AliPayActivity extends Activity {

	private ProgressDialog mProgress = null;
	private Products products;

	//
	// Called when the activity is first created.
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initAlipay();
		products=(Products) getIntent().getSerializableExtra("products");
		if(products==null){
			products=new Products();
			products.setBody("微辣，肉质嫩、烤焦的香味引起胃动");
			products.setPrice("0.01");
			//subject 非空，64位字符（含中文字符）
			products.setSubject("新疆羊肉串");
		}
		
		pay();
		
	}
	
	/**
	 * 支付成功后调用的方法
	 */
	private void defrayComplete() {
		Toast.makeText(AliPayActivity.this,"支付成功后,再此写你的代码逻辑", Toast.LENGTH_SHORT).show();
	}
	

	
	
	/**
	 * 初始化支付宝需要的操作
	 */
	private void initAlipay() {
		// check to see if the MobileSecurePay is already installed.
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		mspHelper.detectMobile_sp();
		
	}

	//
	// get the selected order info for pay.
	String getOrderInfo() {
		String strOrderInfo = "partner=" + "\"" + PartnerConfig.PARTNER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "seller=" + "\"" + PartnerConfig.SELLER + "\"";
		strOrderInfo += "&";
		strOrderInfo += "out_trade_no=" + "\"" + getOutTradeNo() + "\"";
		strOrderInfo += "&";
		strOrderInfo += "subject=" + "\"" + products.getSubject() + "\"";
		strOrderInfo += "&";
		strOrderInfo += "body=" + "\"" + products.getBody() + "\"";
		strOrderInfo += "&";
		strOrderInfo += "total_fee=" + "\"" + products.getPrice() + "\"";
		strOrderInfo += "&";
		strOrderInfo += "notify_url=" + "\"" + PartnerConfig.NOTIFY_URL + "\"";

		return strOrderInfo;
	}

	//
	// get the out_trade_no for an order.
	String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss");
		Date date = new Date();
		String strKey = format.format(date);

		java.util.Random r = new java.util.Random();
		strKey = strKey + r.nextInt();
		strKey = strKey.substring(0, 15);
		return strKey;
	}

	//
	// sign the order info.
	String sign(String signType, String content) {
		return Rsa.sign(content, PartnerConfig.RSA_PRIVATE);
	}

	//
	// get the sign type we use.
	String getSignType() {
		String getSignType = "sign_type=" + "\"" + "RSA" + "\"";
		return getSignType;
	}

	//
	// get the char set we use.
	String getCharset() {
		String charset = "charset=" + "\"" + "utf-8" + "\"";
		return charset;
	}
	
	/**
	 * 进行支付
	 */
	private void pay(){
		//
		// check to see if the MobileSecurePay is already installed.
		MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(this);
		boolean isMobile_spExist = mspHelper.detectMobile_sp();
		if (!isMobile_spExist)
			return;

		// check some info.
		if (!checkInfo()) {
			BaseHelper
					.showDialog(
							AliPayActivity.this,
							"提示",
							"缺少partner或者seller，请在src/com/alipay/android/appDemo4/PartnerConfig.java中增加。",
							R.drawable.infoicon);
			return;
		}

		// start pay for this order.
		try {
			// prepare the order info.
			String orderInfo = getOrderInfo();
			String signType = getSignType();
			String strsign = sign(signType, orderInfo);
			strsign = URLEncoder.encode(strsign);
			String info = orderInfo + "&sign=" + "\"" + strsign + "\"" + "&"
					+ getSignType();

			// start the pay.
			MobileSecurePayer msp = new MobileSecurePayer();
			boolean bRet = msp.pay(info, mHandler, AlixId.RQF_PAY, this);

			if (bRet) {
				// show the progress bar to indicate that we have started
				// paying.
				closeProgress();
				mProgress = BaseHelper.showProgress(this, null, "正在支付", false,
						true);
			} else
				;
		} catch (Exception ex) {
			Toast.makeText(AliPayActivity.this, R.string.remote_call_failed,
					Toast.LENGTH_SHORT).show();
		}
	}

	//
	// check some info.the partner,seller etc.
	private boolean checkInfo() {
		String partner = PartnerConfig.PARTNER;
		String seller = PartnerConfig.SELLER;
		if (partner == null || partner.length() <= 0 || seller == null
				|| seller.length() <= 0)
			return false;

		return true;
	}

	//
	// the handler use to receive the pay result.
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String strRet = (String) msg.obj;

				switch (msg.what) {
				case AlixId.RQF_PAY: {
					//close the progress.
					closeProgress();

					try {
						String memo = "memo=";
						int imemoStart = strRet.indexOf("memo=");
						imemoStart += memo.length();
						int imemoEnd = strRet.indexOf(";result=");
						memo = strRet.substring(imemoStart, imemoEnd);

						ResultChecker resultChecker = new ResultChecker(strRet);

						int retVal = resultChecker.checkSign();
						if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
							BaseHelper.showDialog(
									AliPayActivity.this,
									"提示",
									getResources().getString(
											R.string.check_sign_failed),
									android.R.drawable.ic_dialog_alert);
						} else if (strRet.contains("9000")) {
							defrayComplete();
						} else {
							BaseHelper.showDialog(AliPayActivity.this, "提示",
									checkNo(strRet, memo), R.drawable.infoicon);
						}

					} catch (Exception e) {
						e.printStackTrace();

						BaseHelper.showDialog(AliPayActivity.this, "提示", strRet,
								R.drawable.infoicon);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
	
	/**
	 * 检查错误的编号
	 * @param strRet  当前的编号
	 * @param memo    用于去掉｛ ｝
	 * @return        返回交易提示内容
	 */
	private String checkNo(String strRet, String memo) {
		if (strRet.contains("4000")) {
			memo = "交易失败";
		} else if (strRet.contains("4001")) {
			memo = "数据格式不正确";
		} else if (strRet.contains("4003")) {
			memo = "该用户绑定的支付宝账被冻结或不允许支付";
		} else if (strRet.contains("4004")) {
			memo = "该用户已解除绑定";
		} else if (strRet.contains("4005")) {
			memo = "绑定失败或没有绑定";
		} else if (strRet.contains("4006")) {
			memo = "订单支付失败";
		} else if (strRet.contains("4010")) {
			memo = "重新绑定账户。";
		} else if (strRet.contains("6000")) {
			memo = "支付服务正在进行升级操作。";
		} else if (strRet.contains("6001")) {
			memo = "用户中途取消支付操作。";
		} else if (strRet.contains("6002")) {
			memo = "网络连接异常";
		} else {
			memo = "交易失败";
		}

		return memo;
	}

	//
	// the OnCancelListener for lephone platform.
	static class AlixOnCancelListener implements
			DialogInterface.OnCancelListener {
		Activity mcontext;

		AlixOnCancelListener(Activity context) {
			mcontext = context;
		}

		public void onCancel(DialogInterface dialog) {
			mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	}

	//
	// close the progress bar
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	//
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {

			this.finish();
			return true;
		}

		return false;
	}

	//
	@Override
	public void onDestroy() {
		super.onDestroy();

		try {
			mProgress.dismiss();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}